<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="addPermission(1,'0')">添加权限</el-button>
        </div>

        <el-table border :data="permiseList" row-key="id">
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template v-slot="scope">
              <el-button v-if="scope.row.type===1" type="text" @click="addPermission(2,scope.row.id)">添加</el-button>
              <el-button type="text" @click="editPermission(scope.row.id)">编辑</el-button>
              <el-button type="text" @click="delPerFn(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 放置一个弹层 用来编辑新增节点 -->
        <el-dialog title="新增权限点" :visible="showDialog">
          <!-- 表单 -->
          <el-form ref="perForm" :model="formData" :rules="rules" label-width="120px">
            <el-form-item label="权限名称" prop="name">
              <el-input v-model="formData.name" style="width:90%" />
            </el-form-item>
            <el-form-item label="权限标识" prop="code">
              <el-input v-model="formData.code" style="width:90%" />
            </el-form-item>
            <el-form-item label="权限描述">
              <el-input v-model="formData.description" style="width:90%" />
            </el-form-item>
            <el-form-item label="开启">
              <el-switch
                v-model="formData.enVisible"
                active-value="1"
                inactive-value="0"
              />
            </el-form-item>
          </el-form>
          <el-row slot="footer" type="flex" justify="center">
            <el-col :span="6">
              <el-button size="small" type="primary" @click="addPerFn">确定</el-button>
              <el-button size="small" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permission'
import { tranListToTreeData } from '@/utils'
import { addPermission, getPermissionDetail, updatePermission, delPermission } from '@/api/permission'
export default {
  name: 'Permission',
  data() {
    var validName = (rules, value, callback) => {
      let existList = this.originList.filter(item => item.pid === this.formData.pid)
      if (this.isEdit) {
        existList = existList.filter(item => item.id !== this.formData.id)
      }
      existList.map(item => item.name.trim()).includes(value) ? callback(new Error(`名字${value}已经存在`)) : callback()
    }
    var validCode = (rules, value, callback) => {
      let existLsit = this.originList.map(item => item.code)
      if (this.isEdit) {
        existLsit = this.originList.filter(item => item.id !== this.formData.id).map(item => item.code)
      }
      existLsit.includes(value) ? callback(new Error(`code${value}已经存在`)) : callback()
    }
    return {
      permiseList: [], // 权限列表
      showDialog: false, // 是否显示弹层
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      rules: {
        name: [{ required: true, message: '权限名称不能为空', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }],
        code: [{ required: true, message: '权限标识不能为空', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }]
      },
      isEdit: false, // 编辑的标识
      originList: []// 精简的数组
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    // 删除权限功能
    async delPerFn(id) {
      const resTip = await this.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (resTip === 'cancel') {
        this.$message('取消了删除')
      } else {
        // console.log(id)
        const res = await delPermission(id)
        // 提示
        this.$message.success(res.message)
        // 关闭弹框
        this.showDialog = false
        // 渲染数据
        this.getPermissionList()
      }
    },
    // 点击编辑的按钮
    async editPermission(id) {
      this.isEdit = true
      // 调用接口
      const res = await getPermissionDetail(id)
      // console.log(res)
      // 回填
      this.formData = res.data
      // 显示弹框
      this.showDialog = true
    },
    // 点击确认按钮
    addPerFn() {
      // 兜底验证
      this.$refs.perForm.validate(async valid => {
        if (!valid) return
        // 编辑权限
        if (this.isEdit) {
          const res = await updatePermission(this.formData)
          // 提示
          this.$message.success(res.message)
        } else {
          // 调用接口--添加权限
          const res = await addPermission(this.formData)
          // console.log('88888', res)
          // 提示
          this.$message.success(res.message)
        }
        // 关闭弹框
        this.showDialog = false
        // 渲染数据
        this.getPermissionList()
      })
    },
    // 获取权限列表
    async getPermissionList() {
      const res = await getPermissionList()
      this.originList = res.data.map(item => ({
        id: item.id,
        pid: item.pid,
        name: item.name,
        code: item.code
      }))
      this.permiseList = tranListToTreeData(res.data)
    },
    // 点击添加权限的按钮
    addPermission(type, pid) {
      this.formData.type = type
      this.formData.pid = pid
      this.showDialog = true
      this.isEdit = false
    },
    // 点击取消的按钮
    btnCancel() {
      this.showDialog = false
      this.formData = {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      }
      this.$refs.perForm.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped></style>
